<template>
  <view class="container-wrap" :style="{ height: currentHeight }">
    <view class="title">
      <view @click="isFullScreenFn">价格波动</view>
      <view class="flex">
        <view v-if="[1, 2].includes(button)" style="width: 150px">
          <uni-select v-model="selectValue" dataKey="coalSourceType" dataValue="id" :clear="false"
            :localdata="selectList" @change="conditionChange"></uni-select>
        </view>
        <view v-if="[3].includes(button)" style="width: 150px">
          <uni-select v-model="selectValues" multiple :clear="true" dataValue="id" dataKey="coalSourceType"
            :localdata="selectList" @change="conditionChange"></uni-select>
        </view>
        <view style="width: 60px; margin-left: 10px">
          <uni-select v-model="button" dataKey="name" dataValue="value" :clear="false" :localdata="buttonList"
            @change="buttonChange"></uni-select>
        </view>
      </view>
    </view>
    <view v-if="[3].includes(button)" class="legend-box">
      <view @click="isCalorificChange()">
        <view class="icon">
          <view :style="{ borderTopColor: isCalorific ? '#409efe' : '#c0c0c0' }" class="line calorific"></view>
          <view :style="{ backgroundColor: isCalorific ? '#409efe' : '#c0c0c0' }" class="circle"></view>
        </view>
        <view :style="{ color: isCalorific ? '#409efe' : '#c0c0c0' }">热值</view>
      </view>
      <view @click="isSulfurChange()">
        <view class="icon">
          <view :style="{ borderTopColor: isSulfur ? '#409efe' : '#c0c0c0' }" class="line sulfur"></view>
          <view :style="{ backgroundColor: isSulfur ? '#409efe' : '#c0c0c0' }" class="circle"></view>
        </view>
        <view :style="{ color: isSulfur ? '#409efe' : '#c0c0c0' }">硫分</view>
      </view>
    </view>
    <view class="echart-wrap">
      <echarts-uniapp v-if="[1, 2].includes(button)" ref="priceWaveRef" canvasId="priceWaveChart"
        @touchStart="touchStart" @touchEnd="touchEnd"></echarts-uniapp>
      <echarts-uniapp v-if="[3].includes(button)" ref="qualityWaveRef" canvasId="qualityWaveChart"
        @touchStart="touchStart" @touchEnd="touchEnd"></echarts-uniapp>
    </view>
    <uni-loading v-show="showLoading"></uni-loading>
  </view>
</template>
<script>
  import config from '@/config';
  import { colorList, priceBtnList } from './baseData.js';
  import {
    priceFluctuation,
    getPurQualityUndulate,
    getPurQualityCondition
  } from '@/api/dashboard';
  import { getCurrentDateForParam } from '@/utils/common.js';
  import echartsUniapp from '../common/echarts-uniapp/echarts-uniapp';
  import uniLoading from '../common/uni-loading/uni-loading';
  export default {
    components: {
      echartsUniapp,
      uniLoading
    },
    props: {
      currentHeight: {
        type: String,
        default: '100vh'
      }
    },
    computed: {
      placePath() {
        return config.baseImgUrl + '/up-place.png';
      }
    },
    data() {
      return {
        showLoading: false,
        canSlide: 0,
        touchXStart: 0,
        slideDirection: 0,
        xAxisList: [],
        selectValues: [],
        selectValue: '',
        selectList: [],
        seriesList: [],
        button: 1,
        isCalorific: true,
        isSulfur: true,
        buttonList: priceBtnList,
        option: {
          color: colorList,
          tooltip: {
            trigger: 'axis',
            confine: true,
            responsive: true,
            axisPointer: {
              type: 'line',
              axis: 'auto',
              snap: true
            },
            textStyle: {
              testShadowColor: 'transparent',
              textShadowBlur: 10
            },
            padding: 5
          },
          legend: {
            top: 6,
            data: []
          },
          grid: {
            left: 0,
            right: 0,
            top: 10,
            bottom: 0,
            containLabel: true
          },
          xAxis: {
            type: 'category',
            axisTick: {
              show: false
            },
            data: []
          },
          yAxis: [
            {
              min: 0,
              type: 'value',
              splitLine: {
                show: true,
                lineStyle: {
                  type: 'dashed'
                }
              },
              axisLine: {
                show: true
              },
              axisLabel: {
                formatter: '{value}元'
              }
            }
          ],
          series: []
        }
      };
    },
    async mounted() {
      await this.getPurQualityConditionFn();
      this.priceFluctuationFn();
    },
    methods: {
      isCalorificChange() {
        this.showLoading = true;
        this.isCalorific = !this.isCalorific;
        if (this.isCalorific) {
          if (this.isSulfur) {
            this.option.series = this.seriesList;
          } else {
            const list = this.seriesList.filter((e) => !e.name.includes('硫分'));
            this.option.series = list;
          }
        } else {
          if (this.isSulfur) {
            const list = this.seriesList.filter((e) => !e.name.includes('热值'));
            this.option.series = list;
          } else {
            const list = this.seriesList
              .filter((e) => !e.name.includes('硫分'))
              .filter((e) => !e.name.includes('热值'));
            this.option.series = list;
          }
        }
        this.option.tooltip.formatter = this.getQualityTooltip();
        this.$refs.qualityWaveRef.initChart(this.option);
        setTimeout(() => {
          this.showLoading = false;
        }, 1000);
      },
      isSulfurChange() {
        this.showLoading = true;
        this.isSulfur = !this.isSulfur;
        if (this.isSulfur) {
          if (this.isCalorific) {
            this.option.series = this.seriesList;
          } else {
            const list = this.seriesList.filter((e) => !e.name.includes('热值'));
            this.option.series = list;
          }
        } else {
          if (this.isCalorific) {
            const list = this.seriesList.filter((e) => !e.name.includes('硫分'));
            this.option.series = list;
          } else {
            const list = this.seriesList
              .filter((e) => !e.name.includes('硫分'))
              .filter((e) => !e.name.includes('热值'));
            this.option.series = list;
          }
        }
        this.option.tooltip.formatter = this.getQualityTooltip();
        this.$refs.qualityWaveRef.initChart(this.option);
        setTimeout(() => {
          this.showLoading = false;
        }, 1000);
      },
      isFullScreenFn() {
        if (this.currentHeight === '100vh') {
          return;
        }
        this.$tab.navigateTo('/packageA/pages/purchaseTransport/priceWave');
      },
      touchStart(e) {
        this.touchXStart = e.changedTouches[0].clientX || 0;
      },
      touchEnd(e) {
        const touchXEnd = e.changedTouches[0].clientX;
        if (this.touchXStart - touchXEnd > 0) {
          this.slideDirection = 1;
          this.priceFluctuationFn();
        }
        if (this.touchXStart - touchXEnd < 0) {
          if (this.canSlide !== 0) {
            return;
          }
          this.slideDirection = 0;
          this.priceFluctuationFn();
        }
      },
      conditionChange() {
        this.xAxisList = [];
        this.canSlide = 0;
        this.slideDirection = 0;
        this.isCalorific = true;
        this.isSulfur = true;
        if ([1, 2].includes(this.button)) {
          this.priceFluctuationFn();
        } else {
          this.getPurQualityUndulateFn();
        }
      },
      async buttonChange() {
        this.canSlide = 0;
        this.xAxisList = [];
        this.isSulfur = true;
        this.isCalorific = true;
        this.slideDirection = 0;
        await this.getPurQualityConditionFn();
        if ([1, 2].includes(this.button)) {
          this.priceFluctuationFn();
        } else {
          this.getPurQualityUndulateFn();
        }
      },
      async getPurQualityConditionFn() {
        const flag = this.button === 3 ? false : true;
        const res = await getPurQualityCondition({ flag });
        if (res.code === 0) {
          const result = res.data || [];
          this.selectList = result.map((e) => {
            e.id = `${e.supplierId}${e.coalSourceId}${e.productId}`;
            return e;
          });
          if ([1, 2].includes(this.button)) {
            this.selectValue = this.selectList?.[0]?.id;
          } else {
            this.selectValues = [];
          }
        }
      },
      async getPurQualityUndulateFn() {
        const data = {
          time: this.getDateTime(),
          conditionReqVOS: this.getQualityData()
        };
        this.showLoading = true;
        const res = await getPurQualityUndulate(data);
        if (res.code === 0) {
          this.setQualityYAxisList();
          this.canSlide = res?.data?.[0]?.canSlide;
          const coalStatsInfoVOs = res?.data?.coalStatsInfoVOs || [];
          this.option.legend.show = false;
          this.xAxisList = res?.data?.dateRespVOList || [];
          this.option.tooltip.axisPointer.type = 'line';
          this.option.yAxis[0].min = 0;
          this.option.yAxis[1].min = 0;
          this.option.yAxis[0].max = this.isHasQuality0Data(coalStatsInfoVOs)
            ? 1
            : null;
          this.option.yAxis[1].max = this.isHasQuality1Data(coalStatsInfoVOs)
            ? 1
            : null;
          this.option.tooltip.formatter = this.getQualityTooltip();
          this.option.xAxis.data = this.xAxisList.map((e) => e.label) || [];
          this.seriesList = this.getQualitySeriesList(coalStatsInfoVOs);
          this.option.series = this.seriesList;
          this.$refs.qualityWaveRef.initChart(this.option);
        }
        this.showLoading = false;
      },
      isHasQuality0Data(list) {
        const calorificList =
          list.find((e) => e.dataType === '热值')?.coalProductInfoVOS || [];
        return calorificList.every((e) => !e.dataValue.length);
      },
      isHasQuality1Data(list) {
        const sulfurList =
          list.find((e) => e.dataType === '硫分')?.coalProductInfoVOS || [];
        return sulfurList.every((e) => !e.dataValue.length);
      },
      getQualitySeriesList(list) {
        const calorificList = this.setSeriesName(
          list.find((e) => e.dataType === '热值')?.coalProductInfoVOS || [],
          '热值'
        );
        const sulfurList = this.setSeriesName(
          list.find((e) => e.dataType === '硫分')?.coalProductInfoVOS || [],
          '硫分'
        );
        const calorificSeries = calorificList.map((m, n) => {
          return {
            name: m.coalSourceType,
            type: 'line',
            data: m.dataValue,
            itemStyle: {
              normal: {
                color: colorList[n],
                borderColor: colorList[n],
                borderWidth: 2
              }
            },
            lineStyle: {
              color: colorList[n],
              type: 'solid'
            }
          };
        });
        const sulfurSeries = sulfurList.map((m, n) => {
          return {
            name: m.coalSourceType,
            type: 'line',
            yAxisIndex: 1,
            data: m.dataValue,
            itemStyle: {
              normal: {
                color: colorList[n],
                borderColor: colorList[n],
                borderWidth: 2
              }
            },
            lineStyle: {
              color: colorList[n],
              type: 'dotted'
            }
          };
        });
        return [...calorificSeries, ...sulfurSeries];
      },
      setSeriesName(list, type) {
        return list.map((e) => {
          e.coalSourceType = `${type} ${e.coalSourceType}`;
          return e;
        });
      },
      getQualityTooltip() {
        return (param) => {
          let list = [];
          let result = `${param[0]?.name}\n\r`;
          const calorificList = param.filter((e) =>
            e.seriesName.includes('热值')
          );
          const sulfurList = param.filter((e) => e.seriesName.includes('硫分'));
          if (calorificList.length && sulfurList.length) {
            list = calorificList.map((e, v) => {
              return {
                marker: e.marker,
                name: e.seriesName?.split(' ')?.[1],
                calorific: e.value,
                sulfur: sulfurList[v].value
              };
            });
            list.forEach((e, v) => {
              if (v === list.length - 1) {
                result += `${e.marker} ${e.name} ${e.calorific}卡 ${e.sulfur}%`;
              } else {
                result += `${e.marker} ${e.name} ${e.calorific}卡 ${e.sulfur}%\n\r`;
              }
            });
          } else if (calorificList.length) {
            list = calorificList.map((e, v) => {
              return {
                marker: e.marker,
                name: e.seriesName?.split(' ')?.[1],
                calorific: e.value
              };
            });
            list.forEach((e, v) => {
              if (v === list.length - 1) {
                result += `${e.marker} ${e.name} ${e.calorific}卡`;
              } else {
                result += `${e.marker} ${e.name} ${e.calorific}卡\n\r`;
              }
            });
          } else if (sulfurList.length) {
            list = sulfurList.map((e, v) => {
              return {
                marker: e.marker,
                name: e.seriesName?.split(' ')?.[1],
                sulfur: e.value
              };
            });
            list.forEach((e, v) => {
              if (v === list.length - 1) {
                result += `${e.marker} ${e.name} ${e.sulfur}%`;
              } else {
                result += `${e.marker} ${e.name} ${e.sulfur}%\n\r`;
              }
            });
          } else {
            result += '暂无数据';
          }
          return result;
        };
      },
      async priceFluctuationFn() {
        const data = {
          priceFluctuationType: this.button,
          supplierId: this.getTransportData()?.supplierId,
          coalSourceId: this.getTransportData()?.coalSourceId,
          productId: this.getTransportData()?.productId,
          slideDirection: this.slideDirection,
          reqSource: 1,
          dateTime: this.getDateTime()
        };
        this.showLoading = true;
        const res = await priceFluctuation(data);
        if (res.code === 0) {
          this.setYAxisList();
          this.canSlide = res?.data?.[0]?.canSlide;
          const result = res?.data || [];
          if (this.button === 1) {
            this.option.yAxis[0].max = this.isHas0Data(result) ? 1 : null;
            this.option.tooltip.axisPointer.type = 'line';
          }
          if (this.button === 2) {
            this.option.yAxis[0].max = this.isHas0Data(result) ? 1 : null;
            this.option.yAxis[1].max = this.isHas1Data(result) ? 1 : null;
            this.option.tooltip.axisPointer.type = 'shadow';
          }
          this.option.legend.show = true;
          this.option.tooltip.formatter = this.getTooltip();
          this.option.legend.data = this.getLegendData(result);
          this.xAxisList = result[0]?.dateRespVOList || [];
          this.option.xAxis.data = this.xAxisList.map((e) => e.label) || [];
          this.option.series = this.getSeriesList(result);
          this.$refs.priceWaveRef.initChart(this.option);
        }
        this.showLoading = false;
      },
      getDateTime() {
        let dateTime = '';
        if (!this.xAxisList.length) {
          dateTime = getCurrentDateForParam(new Date());
        }
        if (this.xAxisList.length) {
          if (!this.slideDirection) {
            dateTime = this.xAxisList[0]?.value?.split('_')?.[0];
          }
          if (this.slideDirection) {
            dateTime =
              this.xAxisList[this.xAxisList.length - 1]?.value?.split('_')?.[1];
          }
        }
        return dateTime;
      },
      isHas0Data(list) {
        return list?.[0]?.dataInfoList?.every((m) => !m.dataValue?.length);
      },
      isHas1Data(list) {
        return list?.[1]?.dataInfoList?.every((m) => !m.dataValue?.length);
      },
      getTooltip() {
        return (param) => {
          let result = `${param[0]?.name}\n\r`;
          param.forEach((e, v) => {
            if (v === param.length - 1) {
              result += `${e.marker} ${e.seriesName} ${e.value}${e.seriesName === '数量' ? '吨' : '元'
                }`;
            } else {
              result += `${e.marker} ${e.seriesName} ${e.value}${e.seriesName === '数量' ? '吨' : '元'
                }\n\r`;
            }
          });
          return result;
        };
      },
      getLegendData(list) {
        const result = list.map((e) => {
          return (e.dataInfoList || []).map((m) => {
            return m.durationType;
          });
        });
        return result.flat(Infinity);
      },
      getSeriesList(list) {
        const result = list.map((e) => {
          return (e.dataInfoList || []).map((m) => {
            if (m.durationType === '数量') {
              return {
                name: m.durationType,
                type: 'bar',
                barWidth: 10,
                yAxisIndex: 1,
                data: m.dataValue || []
              };
            } else {
              return {
                name: m.durationType,
                type: 'line',
                data: m.dataValue || []
              };
            }
          });
        });
        return result.flat(Infinity);
      },
      setYAxisList() {
        if (this.button === 1) {
          this.option.grid.top = 40;
          this.option.yAxis = [
            {
              min: 0,
              type: 'value',
              splitLine: {
                show: true,
                lineStyle: {
                  type: 'dashed'
                }
              },
              axisLine: {
                show: true
              },
              axisLabel: {
                formatter: '{value}元'
              }
            }
          ];
        }
        if (this.button === 2) {
          this.option.grid.top = 60;
          this.option.yAxis = [
            {
              min: 0,
              type: 'value',
              splitLine: {
                show: true,
                lineStyle: {
                  type: 'dashed'
                }
              },
              axisLine: {
                show: true
              },
              axisLabel: {
                formatter: '{value}元'
              }
            },
            {
              min: 0,
              type: 'value',
              splitLine: {
                show: true,
                lineStyle: {
                  type: 'dashed'
                }
              },
              axisLine: {
                show: true
              },
              axisLabel: {
                formatter: '{value}吨'
              }
            }
          ];
        }
      },
      setQualityYAxisList() {
        this.option.grid.top = 20;
        this.option.yAxis = [
          {
            min: 0,
            type: 'value',
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true
            },
            axisLabel: {
              formatter: '{value}卡'
            }
          },
          {
            min: 0,
            type: 'value',
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true
            },
            axisLabel: {
              formatter: '{value}%'
            }
          }
        ];
      },
      getTransportData() {
        return this.selectList.find((e) => e.id === this.selectValue);
      },
      getQualityData() {
        if (!this.selectValues.length) {
          return this.selectList.map((e) => {
            return this.getParamsData(e);
          });
        }
        return this.selectList
          .filter((e) => this.selectValues.includes(e.id))
          .map((e) => {
            return this.getParamsData(e);
          });
      },
      getParamsData(e) {
        return {
          productId: e.productId,
          purchaserId: e.purchaserId,
          coalSourceId: e.coalSourceId,
          supplierId: e.supplierId,
          coalSourceName: e.coalSourceName,
          productName: e.productName,
          purchaserName: e.purchaserName
        };
      }
    }
  };
</script>
<style lang="scss" scoped>
  .container-wrap {
    position: relative;
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 15px 10px;
    background-color: #ffffff;
    border-radius: 8px;

    .title {
      display: flex;
      font-size: 14px;
      color: #000000;
      font-weight: 600;
      padding-bottom: 11px;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #e6e6e6;
    }

    .echart-wrap {
      flex: 1;
      height: 0;
    }

    .place-wrap {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 10px 0;
    }

    .flex {
      display: flex;
    }

    .flex-direction {
      flex-direction: column;
    }
  }

  .legend-box {
    display: flex;
    align-items: center;
    padding: 0 20px;
    justify-content: flex-end;

    >view {
      display: flex;
      align-items: center;
      font-size: 12px;
      padding: 10px 0;

      .icon {
        position: relative;
        width: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .circle {
        width: 11px;
        height: 11px;
        border-radius: 11px;
      }

      .line {
        position: absolute;
        left: 8px;
        width: 25px;
        top: 5px;
        border-top-width: 1px;
      }

      .calorific {
        border-top-style: solid;
      }

      .sulfur {
        border-top-style: dotted;
      }
    }
  }
</style>